﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using XZL.Web.Biz;
using XZL.Web.Da;
using XZL.Web.Entity;
using XZL.Web.MVC.WXModel;

namespace XZL.Web.MVC.Controllers
{
    public class MyInfoController : Controller
    {
        string address = ConfigurationManager.AppSettings["ServerAddress"];
        string appid = ConfigurationManager.AppSettings["appid"];
        string appsecret = ConfigurationManager.AppSettings["appsecret"];
        string redirecturi = ConfigurationManager.AppSettings["redirecturi"];
        string appkey = ConfigurationManager.AppSettings["appkey"];
        string mchid = ConfigurationManager.AppSettings["mchid"];

        /// <summary>
        /// 获取session数据
        /// </summary>
        /// <returns></returns>
        private UserInfo GetMyInfo()
        {
            UserInfo user = new UserInfo();
            if (HttpContext.Session["MyInfo"] != null)
            {
                user = HttpContext.Session["MyInfo"] as UserInfo;
            }
            else
            {
                string url = Request.Url.AbsoluteUri.ToString();

                string inviteID = "1";
                if (HttpContext.Session["InviteID"] != null)
                {
                    inviteID = HttpContext.Session["InviteID"].ToString();
                }
                string link1 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirecturi;
                string link2 = "&response_type=code&scope=snsapi_userinfo&state=" + url;
                Response.Redirect(link1 + inviteID + link2);
            }
            return user;
        }

        /// <summary>
        ///  我的主页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            UserInfo user = GetMyInfo();

            ViewBag.NickName = user.NickName;
            ViewBag.ReferrerName = user.ReferrerName;
            ViewBag.TypeID = user.UserTypeID;

            //手机号 3-4-4格式
            //string phone = user.MobilePhone;
            //string newPhone = "";
            //if (phone.Length > 10)
            //{
            //    newPhone = phone.Substring(0, 3) + " " + phone.Substring(3, 4) + " " + phone.Substring(7, 4);
            //}
            //ViewBag.MobilePhone = newPhone;

            //string rPhone = user.ReferrerPhone;
            //string newRPhone = "";
            //if (rPhone.Length > 10)
            //{
            //    newRPhone = rPhone.Substring(0, 3) + " " + rPhone.Substring(3, 4) + " " + rPhone.Substring(7, 4);
            //}
            //ViewBag.ReferrerPhone = newRPhone;

            if (user.HeadPortrait == null || user.HeadPortrait == "")
            {
                ViewBag.HeadImg = "~/image/defaultHead2.jpg";
            }
            else
            {
                ViewBag.HeadImg = user.HeadPortrait;
            }

            return View();
        }

        /// <summary>
        /// 邀请页
        /// </summary>
        /// <returns></returns>
        public ActionResult Invite()
        {
            UserInfo user = GetMyInfo();
            ViewBag.UserNum = user.UserNum;
            ViewBag.NickName = user.NickName;
            ViewBag.HeadImg = user.HeadPortrait;
            return View();
        }

        /// <summary>
        /// 二维码邀请
        /// </summary>
        /// <returns></returns>
        public ActionResult InviteEWM()
        {
            string str = Request.QueryString["Code"];
            int code = 0;
            try
            {
                code = Convert.ToInt32(str);
            }
            catch { }
            Proc_UserInfo_SelectByUserNumResult user = UserBiz.GetUserInfoByUserNum(code);
            if (user != null)
            {
                string nick = user.WeiXinName;
                string img = user.HeadPortrait;
                string link = address + "Home/Index?InviteID=" + code;

                wxshareHandler wxsh = new wxshareHandler();
                string token = wxsh.GetToken();
                string ticket = wxsh.GetTicket(token);
                int timestamp = wxsh.ConvertDateTimeInt(DateTime.Now);
                string nonceStr = wxsh.GenerateCheckCode(16);
                string url = address + "MyInfo/InviteEWM?Code=" + code;
                string sign = wxsh.GetSignature(ticket, nonceStr, timestamp.ToString(), url);

                //分享参数
                ViewBag.AppID = appid;
                ViewBag.Token = token;
                ViewBag.Ticket = ticket;
                ViewBag.Timestamp = timestamp.ToString();
                ViewBag.NonceStr = nonceStr;
                ViewBag.Sign = sign;
                ViewBag.Url = url;
                ViewBag.Address = address;

                //邀请人信息
                ViewBag.Link = link;
                ViewBag.HeadImg = img;
                ViewBag.UserNum = code;
                ViewBag.NickName = nick;
            }
            return View();
        }

        /// <summary>
        /// 链接邀请
        /// </summary>
        /// <returns></returns>
        public ActionResult InviteByLink()
        {
            string str = Request.QueryString["Code"];
            int code = 0;
            try
            {
                code = Convert.ToInt32(str);
            }
            catch { }
            Proc_UserInfo_SelectByUserNumResult user = UserBiz.GetUserInfoByUserNum(code);
            if (user != null)
            {
                string nick = user.WeiXinName;
                string img = user.HeadPortrait;
                string link = address + "Home/Index?InviteID=" + code;

                //获取分享参数
                wxshareHandler wxsh = new wxshareHandler();
                string token = wxsh.GetToken();
                string ticket = wxsh.GetTicket(token);
                int timestamp = wxsh.ConvertDateTimeInt(DateTime.Now);
                string nonceStr = wxsh.GenerateCheckCode(16);
                string url = address + "MyInfo/InviteByLink?Code=" + code;
                string sign = wxsh.GetSignature(ticket, nonceStr, timestamp.ToString(), url);

                //分享参数
                ViewBag.AppID = appid;
                ViewBag.Token = token;
                ViewBag.Ticket = ticket;
                ViewBag.Timestamp = timestamp.ToString();
                ViewBag.NonceStr = nonceStr;
                ViewBag.Sign = sign;
                ViewBag.Url = url;
                ViewBag.Address = address;

                //邀请人信息
                ViewBag.Link = link;
                ViewBag.HeadImg = img;
                ViewBag.UserNum = code;
                ViewBag.NickName = nick;
            }

            return View();
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdatePwd()
        {
            UserInfo user = GetMyInfo();
            string phone = user.MobilePhone;
            string newPhone = "";
            if (phone.Length > 10)
            {
                newPhone = phone.Substring(0, 3) + " " + phone.Substring(3, 4) + " " + phone.Substring(7, 4);
            }
            ViewBag.Phone = newPhone;
            ViewBag.UserID = user.UserID;

            return View();
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpdatePwd(FormCollection fc)
        {
            string userID = fc["UserID"];
            string phone = fc["Phone"];
            phone = phone.Replace(" ", "");
            string code = fc["MobileCode"];
            string pwd = fc["Pwd"];
            pwd = CommonMethods.StrToMD5(pwd);
            int res = UserBiz.UpdatePwd(userID, code, pwd);
            if (res == 0)
            {
                return RedirectToAction("UpdateSuccessful", "MyInfo");
            }
            else
            {
                ViewBag.Phone = phone;
                ViewBag.UserID = userID;
                ViewBag.ErrorInfo = "验证码错误，请重新输入！";
            }
            return View();
        }

        /// <summary>
        /// 更新密码成功
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateSuccessful()
        {
            return View();
        }

        /// <summary>
        /// 我的积分
        /// </summary>
        /// <returns></returns>
        public ActionResult MyScore()
        {
            UserInfo user = GetMyInfo();
            DateTime now = DateTime.Now;
            DateTime start = new DateTime(now.Year, now.Month, 1);
            DateTime end = new DateTime(now.Year, now.Month + 1, 1);
            double? count = 0;
            int? userCount = 0;

            string str = Request.QueryString["Date"];
            if (str != null)
            {
                try
                {
                    DateTime date = Convert.ToDateTime(str);
                    start = new DateTime(date.Year, date.Month, 1);
                    end = new DateTime(date.AddMonths(1).Year, date.AddMonths(1).Month, 1);
                }
                catch
                {
                }
            }

            ViewBag.Year = start.Year;
            ViewBag.Month = start.Month;

            //个人消费记录
            List<Proc_AccountLog_UserExpenseResult> lsUserExpense = UserBiz.GetUserExpense(user.UserID, start, end, ref count);
            if (count == null)
            {
                ViewBag.UserExpense = 0;
            }
            else
            {
                ViewBag.UserExpense = count.Value;
            }
            ViewBag.UserExpenseList = lsUserExpense;

            //推广消费记录
            List<Proc_AccountLog_PromoteExpenseResult> lsPromoteExpense = UserBiz.GetPromoteExpense(user.UserID, start, end, ref count,ref userCount);
            if (count == null)
            {
                ViewBag.PromoteExpense = 0;
            }
            else
            {
                ViewBag.PromoteExpense = count.Value;
            }
            if (userCount == null)
            {
                ViewBag.PromoteUser = 0;
            }
            else
            {
                ViewBag.PromoteUser = userCount.Value;
            }
            ViewBag.PromoteExpenseList = lsPromoteExpense;

            ViewBag.MyScore = user.Account;
            return View();
        }

        /// <summary>
        /// 我的账户
        /// </summary>
        /// <returns></returns>
        public ActionResult MyAccount()
        {
            UserInfo user = GetMyInfo();
            DateTime now = DateTime.Now;
            DateTime start = new DateTime(now.Year, now.Month, 1);
            DateTime end = new DateTime(now.Year, now.Month + 1, 1);
            double? count = 0;
            int? userCount = 0;

            string str = Request.QueryString["Date"];
            if (str != null)
            {
                try
                {
                    DateTime date = Convert.ToDateTime(str);
                    start = new DateTime(date.Year, date.Month, 1);
                    end = new DateTime(date.AddMonths(1).Year, date.AddMonths(1).Month, 1);
                }
                catch
                {
                }
            }

            ViewBag.Year = start.Year;
            ViewBag.Month = start.Month;

            //个人消费记录
            List<Proc_AccountLog_UserExpenseResult> lsUserExpense = UserBiz.GetUserExpense(user.UserID, start, end, ref count);
            if (count == null)
            {
                ViewBag.UserExpense = 0;
            }
            else
            {
                ViewBag.UserExpense = count.Value;
            }
            ViewBag.UserExpenseList = lsUserExpense;

            //推广消费记录
            List<Proc_AccountLog_PromoteExpenseResult> lsPromoteExpense = UserBiz.GetPromoteExpense(user.UserID, start, end, ref count, ref userCount);
            if (count == null)
            {
                ViewBag.PromoteExpense = 0;
            }
            else
            {
                ViewBag.PromoteExpense = count.Value;
            }
            if (userCount == null)
            {
                ViewBag.PromoteUser = 0;
            }
            else
            {
                ViewBag.PromoteUser = userCount.Value;
            }
            ViewBag.PromoteExpenseList = lsPromoteExpense;

            //小组推广消费记录
            List<Proc_AccountLog_TeamExpenseResult> lsTeamExpense = UserBiz.GetTeamExpense(user.UserID, start, end, ref count, ref userCount);
            if (count == null)
            {
                ViewBag.TeamExpense = 0;
            }
            else
            {
                ViewBag.TeamExpense = count.Value;
            }
            if (userCount == null)
            {
                ViewBag.TeamUser = 0;
            }
            else
            {
                ViewBag.TeamUser = userCount.Value;
            }
            ViewBag.TeamExpenseList = lsTeamExpense;


            ViewBag.MyScore = user.Account;
            return View();
        }

        /// <summary>
        /// 我的课程
        /// </summary>
        /// <returns></returns>
        public ActionResult MyCourse()
        {
            UserInfo user = GetMyInfo();
            List<Proc_UserCourse_MyCourseListResult> ls = CourseBiz.GetMyCourseList(user.UserID, 1);
            List<Proc_UserCourse_MyCourseListResult> lsPay = CourseBiz.GetMyCourseList(user.UserID, 2);
            List<Proc_UserCourse_MyCourseListResult> lsGet = CourseBiz.GetMyCourseList(user.UserID, 4);
            ViewBag.CourseList = ls;
            ViewBag.PayList = lsPay;
            ViewBag.GetList = lsGet;
            ViewBag.InviteID = user.UserNum;
            return View();
        }

        /// <summary>
        /// 我的评价
        /// </summary>
        /// <returns></returns>
        public ActionResult MyComment()
        {
            UserInfo user = GetMyInfo();
            List<Proc_Comment_MyCommentResult> ls = CourseBiz.GetMyCommentList(user.UserID);
            ViewBag.CommentList = ls;
            ViewBag.InviteID = user.UserNum;
            return View();
        }

        /// <summary>
        /// 我的收藏
        /// </summary>
        /// <returns></returns>
        public ActionResult MyCollect()
        {
            UserInfo user = GetMyInfo();
            List<Proc_UserCourse_MyCourseListResult> ls = CourseBiz.GetMyCourseList(user.UserID, 3);
            ViewBag.CourseList = ls;
            ViewBag.InviteID = user.UserNum;
            return View();
        }

        /// <summary>
        /// 关于我们
        /// </summary>
        /// <returns></returns>
        public ActionResult AboutUs()
        {
            return View();
        }

        /// <summary>
        /// 申请代理宣传页
        /// </summary>
        /// <returns></returns>
        public ActionResult ApplyProxy()
        {
            return View();
        }

        /// <summary>
        /// 申请代理
        /// </summary>
        /// <returns></returns>
        public ActionResult ApplyAgent()
        {
            UserInfo user = GetMyInfo();
            return View();
        }

        /// <summary>
        /// 申请代理[提交数据]
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ApplyAgent(FormCollection fc)
        {
            UserInfo user = GetMyInfo();
            string userID = user.UserID;
            int type = 1;
            string realName = fc["RealName"];
            string city = fc["City"];
            string idCard = fc["IDCard"];
            string phone = fc["Phone"];
            string address = fc["Address"];
            string company = fc["Company"];
            string position = fc["Position"];
            string reson = fc["Reason"];
            bool b = UserBiz.AddApplyInfo(userID, type, reson, phone, realName, city, idCard, address, company, position, "");
            if (b)
            {
                return RedirectToAction("ApplySucceful", "MyInfo");
            }
            else
            {
                ViewBag.ErrorInfo = "申请失败，请重试！";
            }
            return View();
        }

        /// <summary>
        /// 申请讲师
        /// </summary>
        /// <returns></returns>
        public ActionResult ApplyTeacher()
        {
            return View();
        }


        /// <summary>
        /// 申请讲师[提交数据]
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ApplyTeacher(FormCollection fc)
        {
            UserInfo user = GetMyInfo();
            string userID = user.UserID;
            int type = 3;
            string realName = fc["RealName"];
            string city = fc["City"];
            string idCard = fc["IDCard"];
            string phone = fc["Phone"];
            string time = fc["Time"];
            string position = fc["Position"];
            string reson = fc["Reason"];
            bool b = UserBiz.AddApplyInfo(userID, type, reson, phone, realName, city, idCard, "", "", position, time);
            if (b)
            {
                return RedirectToAction("ApplySucceful", "MyInfo");
            }
            else
            {
                ViewBag.ErrorInfo = "申请失败，请重试！";
            }
            return View();
        }

        /// <summary>
        /// 申请加盟
        /// </summary>
        /// <returns></returns>
        public ActionResult ApplyLeague()
        {
            return View();
        }

        /// <summary>
        /// 申请加盟[提交数据]
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ApplyLeague(FormCollection fc)
        {
            UserInfo user = GetMyInfo();
            string userID = user.UserID;
            int type = 2;
            string realName = fc["RealName"];
            string city = fc["City"];
            string idCard = fc["IDCard"];
            string phone = fc["Phone"];
            string address = fc["Address"];
            string company = fc["Company"];
            string position = fc["Position"];
            string reson = fc["Reason"];
            bool b = UserBiz.AddApplyInfo(userID, type, reson, phone, realName, city, idCard, address, company, position, "");
            if (b)
            {
                return RedirectToAction("ApplySucceful", "MyInfo");
            }
            else
            {
                ViewBag.ErrorInfo = "申请失败，请重试！";
            }
            return View();
        }

        /// <summary>
        /// 意见反馈
        /// </summary>
        /// <returns></returns>
        public ActionResult UserIdea()
        {
            return View();
        }

        /// <summary>
        /// 意见反馈
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserIdea(FormCollection fc)
        {
            UserInfo user = GetMyInfo();
            string userID = user.UserID;
            int type = 4;
            string phone = fc["Phone"];
            string reson = fc["Reason"];
            bool b = UserBiz.AddApplyInfo(userID, type, reson, phone, "", "", "", "", "", "", "");
            if (b)
            {
                return RedirectToAction("ApplySucceful", "MyInfo");
            }
            else
            {
                ViewBag.ErrorInfo = "提交失败，请重试！";
            }
            return View();
        }

        /// <summary>
        /// 申请成功
        /// </summary>
        /// <returns></returns>
        public ActionResult ApplySucceful()
        {
            return View();
        }

        /// <summary>
        /// 正在开发中...
        /// </summary>
        /// <returns></returns>
        public ActionResult NoPage()
        {
            return View();
        }
    }
}